<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>学生信息管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .action-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .left-group {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .filter-group {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .class-filter {
            padding: 6px 12px;
            border: 1px solid #ddd;
            /* 浅灰边框 */
            border-radius: 4px;
            width: 100px;
            /* 略窄于搜索框 */
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th {
            background-color: #e3f2fd;
            padding: 12px;
            text-align: left;
        }

        td {
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        button {
            padding: 6px 12px;
            cursor: pointer;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }

        button#addBtn {
            background-color: #4CAF50;
            /* 绿色按钮 */
            padding: 8px 20px;
            border-radius: 4px;
        }

        button.delete {
            background-color: #f44336;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.4);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            width: 400px;
            border-radius: 8px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        input,
        select {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .search-box {
            width: 220px;
            /* 与原图搜索框宽度匹配 */
            padding: 8px 12px;
            border: 1px solid #000000;
            /* 黑色边框 */
            border-radius: 4px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>学生信息管理</h1>

        <div class="action-bar">
            <div class="left-group">
                <button id="addBtn" onclick="showAddModal()">添加学生</button>
                <input type="text" id="searchInput" placeholder="搜索姓名或智学号..." class="search-box">
            </div>

            <!-- 右侧筛选区 -->
            <div class="filter-group">
                <label>班级：</label>
                <select class="class-filter" id="classFilter">
                    <option value="all">全部</option>
                    <option value="2">2班</option>
                    <option value="6">6班</option>
                    <option value="7">7班</option>
                </select>
            </div>
        </div>

        <table id="studentTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>智学号</th>
                    <th>密码</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>班级</th>
                    <th>选科组合</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 数据将通过JavaScript动态插入 -->
            </tbody>
        </table>

        <!-- 添加/编辑模态框 -->
        <div id="editModal" class="modal">
            <div class="modal-content">
                <h2 id="modalTitle">添加学生</h2>
                <form id="studentForm" onsubmit="handleFormSubmit(event)">
                    <div class="form-group">
                        <label>智学号:</label>
                        <input type="text" id="智学号" required>
                    </div>
                    <div class="form-group">
                        <label>密码:</label>
                        <input type="text" id="密码" required>
                    </div>
                    <div class="form-group">
                        <label>姓名:</label>
                        <input type="text" id="姓名" required>
                    </div>
                    <div class="form-group">
                        <label>性别:</label>
                        <select id="性别">
                            <option value="男">男</option>
                            <option value="女">女</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>班级:</label>
                        <input type="number" id="班级" min="1" required>
                    </div>
                    <div class="form-group">
                        <label>选科组合:</label>
                        <input type="text" id="选科组合" value="理、化、生" readonly>
                    </div>
                    <button type="submit">提交</button>
                    <button type="button" onclick="closeModal()">取消</button>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 模拟初始数据（实际使用时需要对接后端API）
        let students = [];

        // 当前编辑的学生ID
        let currentEditId = null;

        // 显示添加模态框
        function showAddModal() {
            currentEditId = null;
            document.getElementById('modalTitle').textContent = '添加学生';
            document.getElementById('editModal').style.display = 'block';
            document.getElementById('选科组合').value = '理、化、生';
        }

        // 显示编辑模态框
        function showEditModal(id) {
            const student = students.find(s => s.id === id);
            if (student) {
                currentEditId = id;
                document.getElementById('modalTitle').textContent = '编辑学生';
                document.getElementById('智学号').value = student.智学号;
                document.getElementById('密码').value = student.密码;
                document.getElementById('姓名').value = student.姓名;
                document.getElementById('性别').value = student.性别;
                document.getElementById('班级').value = student.班级;
                document.getElementById('选科组合').value = student.选科组合;
                document.getElementById('editModal').style.display = 'block';
            }
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        // 处理表单提交
        async function handleFormSubmit(event) {
            event.preventDefault();
            const studentData = {
                智学号: document.getElementById('智学号').value,
                密码: document.getElementById('密码').value,
                姓名: document.getElementById('姓名').value,
                性别: document.getElementById('性别').value,
                班级: document.getElementById('班级').value,
                选科组合: document.getElementById('选科组合').value
            };

            // 这里应该调用后端API
            if (currentEditId) {
                studentData["ID"] = currentEditId;
                // 更新操作
                try {
                    // 发送POST请求
                    response = await fetch('/api/editStudent', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            studentData: studentData
                        })
                    });
                    const row = document.querySelector(`tr[data-id="${currentEditId}"]`);
                    if (row) {
                        row.innerHTML = `
                            <td>${studentData.ID}</td>
                            <td>${studentData.智学号}</td>
                            <td>${studentData.密码}</td>
                            <td>${studentData.姓名}</td>
                            <td>${studentData.性别}</td>
                            <td>${studentData.班级}</td>
                            <td>${studentData.选科组合}</td>
                            <td>
                                <button onclick="showEditModal(${studentData.id})">编辑</button>
                                <button class="delete" onclick="deleteStudent(${studentData.id})">删除</button>
                            </td>
                            `;
                    }
                } catch (error) {
                    showError(error.message);
                }
            } else {
                // 新增操作
                try {
                    // 发送POST请求
                    response = await fetch('/api/addStudent', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            studentData: studentData
                        })
                    });
                    insertStu = await response.json()
                    // 获取新数据并更新表格                    
                    students.unshift(insertStu[0]);
                    renderTable();

                } catch (error) {
                    showError(error.message);
                }
            }

            closeModal();
        }

        // 删除学生
        async function deleteStudent(id) {
            if (confirm('确定要删除这个学生吗？')) {
                try {
                    const response = await fetch('/api/deleteStudent', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            id
                        })
                    });
                    console.log(response.ok)
                    if (response.ok) {
                        // 直接通过 data-id 属性定位元素
                        const row = document.querySelector(`tr[data-id="${id}"]`);
                        if (row) {
                            row.style.opacity = '0'; // 添加过渡效果
                            setTimeout(() => row.remove(), 300);
                        }
                    } else {
                        throw new Error(`删除失败，状态码: ${response.status}`);
                    }
                } catch (error) {
                    console.error('删除错误:', error);
                }
            }
        }

        // 初始化表格
        function renderTable() {
            const tbody = document.querySelector('#studentTable tbody');
            tbody.innerHTML = students.map(student => `
                <tr data-id="${student.id}">
                    <td>${student.id}</td>
                    <td>${student.智学号}</td>
                    <td>${student.密码}</td>
                    <td>${student.姓名}</td>
                    <td>${student.性别}</td>
                    <td>${student.班级}</td>
                    <td>${student.选科组合}</td>
                    <td>
                        <button onclick="showEditModal(${student.id})">编辑</button>
                        <button class="delete" onclick="deleteStudent(${student.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 搜索功能
        document.getElementById('searchInput').addEventListener('input', async function (e) {
            const searchTerm = e.target.value.toLowerCase();
            try {
                // 显示加载状态
                showLoading();

                // 发送POST请求
                const response = await fetch('/api/getStudentsLikeNameOrStuid', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        nameOrStuid: searchTerm
                    })
                });

                if (!response.ok) throw new Error(`请求失败：${response.status}`);

                // 获取新数据并更新表格
                const result = await response.json();
                students = result;
                renderTable();

            } catch (error) {
                showError(error.message);
            }
        });

        // 初始化渲染
        renderTable();

        // 点击模态框外部关闭
        window.onclick = function (event) {
            if (event.target.className === 'modal') {
                closeModal();
            }
        }

        //页面载入时从后台读取数据
        document.addEventListener('DOMContentLoaded', async () => {
            try {
                // 显示加载状态
                showLoading();

                // 调用后端API获取数据（需要您实现）
                const response = await fetch('/api/getAllStudents');
                //if (!response.ok) throw new Error('数据加载失败');

                students = await response.json();
                renderTable();

            } catch (error) {
                // 错误处理
                showError(error.message);
            }
        });

        // 班级筛选功能
        document.getElementById('classFilter').addEventListener('change', async function () {
            const selectedClass = this.value;

            try {
                // 显示加载状态
                showLoading();

                // 发送POST请求
                const response = await fetch('/api/getStudentsByClass', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        classid: selectedClass === '全部' ? "all" : selectedClass
                    })
                });

                if (!response.ok) throw new Error(`请求失败：${response.status}`);

                // 获取新数据并更新表格
                const result = await response.json();
                students = result;
                renderTable();

            } catch (error) {
                showError(error.message);
            }
        });

        // 显示加载状态（复用已有加载样式）
        function showLoading() {
            document.querySelector('#studentTable tbody').innerHTML = `
        <tr>
            <td colspan="8" style="text-align: center; padding: 20px;">
                <div class="loader"></div>
                <div>数据加载中...</div>
            </td>
        </tr>`;
        }

        // 显示错误信息（复用已有错误处理）
        function showError(message) {
            document.querySelector('#studentTable tbody').innerHTML = `
        <tr>
            <td colspan="8" style="text-align: center; color: red; padding: 20px;">
                错误：${message}
            </td>
        </tr>`;
        }
    </script>
</body>

</html>